import { statePool } from './compiler/state.js'
import { updateDom} from './render.js'

function useReactive(target) {
    if (!isObject(target)) { return target }
    return createReactiveObject(target, mutableHandler)
}

function createReactiveObject(target, mutableHandler) {

    const observer = new Proxy(target, mutableHandler)

    return observer
}

// const proxy = new Proxy(target,{
//     set (target,key,value,receiver){
//         console.log(target,key,value, receiver)
//     }
// })

// const baseHandler = {
//     set (target,key,receiver){
//         console.log(111,target,key,receiver)
//     }
// }
const get = createGetter()
const set = createSetter()

const mutableHandler = {
    get,
    set
}

function createSetter() {

    return function set(target, key, value, receiver) {
        console.log('---setter---')
        const isKeyExist = hasOwnProperty(target, key)
        //  value = '我是set新设置的值 ：' + value + '-cen'
        if (!isKeyExist) {
            console.log('add new proper：', key)
        } else if (!isEqual(target[key], value)) {
            console.log('newvalue!==prevalue')            
            updateDom(statePool,key,value)
        }
        const res = Reflect.set(target, key, value, receiver)
        return res
    }
}
function createGetter() {
    return function get(target, key, receiver) {
        const res = Reflect.get(target, key, receiver)
        console.log('---getter---')
        return res
    }
}
function isObject(target) {
    return typeof target === 'object' && target !== null
}
function isEqual(val, preVal) {
    return val === preVal
}
function hasOwnProperty(target, key) {
    return Object.hasOwnProperty.call(target, key)
}
export {
    useReactive
}